package wang.chunfan.code.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/6/2 18:31
 **/
public class TimeServer {
    public void bind(int port) throws Exception {
        // 配置服务端的 NIO 线程组,实际就是 Reactor 线程组（可以看第二章的图）
        // Readctor Thread 表示在一个线程中循环调用 selector.select()
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // 用于接受连接
        EventLoopGroup workerGroup = new NioEventLoopGroup(); // 用于网络读写
        try {
            // 启动 NIO 服务端的辅助启动类，目的是降低服务端开发复杂度
            ServerBootstrap b = new ServerBootstrap();
            //配置启动类
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 创建的 Channel,类似于 JDK 的 ServerSocketChannel
                    .option(ChannelOption.SO_BACKLOG, 1024) // 配置 NioServerSocketChannel 的 TCP 参数
                    .childHandler(new ChildChannelHandler()); // ServerSocketChannel 的 child 为 SocketChannel I/O 事件处理类
            // 绑定端口，调用同步阻塞方法启动，获取回调结果 ChannelFuture
            ChannelFuture f = b.bind(port).sync();
            System.out.println("The time server is start in port:" + port);
            // 等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            // TimeServerHandler 用于处理 socketChannel 中的事件
            socketChannel.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new TimeServer().bind(port);
    }
}
